package com.jdew.thkj.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.RelativeSizeSpan;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ali.auth.third.core.MemberSDK;
import com.ali.auth.third.core.callback.LoginCallback;
import com.ali.auth.third.core.model.Session;
import com.ali.auth.third.login.LoginService;
import com.ali.auth.third.ui.context.CallbackContext;
import com.alibaba.baichuan.android.trade.AlibcTrade;
import com.alibaba.baichuan.android.trade.callback.AlibcTradeCallback;
import com.alibaba.baichuan.android.trade.model.AlibcShowParams;
import com.alibaba.baichuan.android.trade.model.OpenType;
import com.alibaba.baichuan.android.trade.model.TradeResult;
import com.alibaba.baichuan.android.trade.page.AlibcBasePage;
import com.alibaba.baichuan.android.trade.page.AlibcPage;
import com.alibaba.baichuan.trade.biz.AlibcConstants;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.jdew.thkj.R;
import com.jdew.thkj.base.BaseActivity;
import com.jdew.thkj.bean.CouponBean;
import com.jdew.thkj.bean.ScoreBean;
import com.jdew.thkj.bean.TbDetailBean;
import com.jdew.thkj.bean.TbImageDetailBean;
import com.jdew.thkj.bean.TklBean;
import com.jdew.thkj.dialog.CommonDialog;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.manager.GlideImageLoader;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.utils.CleanCacheUtil;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;
import com.jdew.thkj.utils.WeiboDialogUtils;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by yangyang on 2017/9/14.
 */

public class TbProductDetailActivity extends BaseActivity {
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.name)
    TextView name;
    @Bind(R.id.upgrade)
    TextView upgrade;
    @Bind(R.id.ymoney)
    TextView ymoney;
    @Bind(R.id.quanhou)
    TextView quanhou;
    @Bind(R.id.salenum)
    TextView salenum;
    @Bind(R.id.share)
    TextView share;
    @Bind(R.id.copy)
    TextView copy;
    @Bind(R.id.money)
    TextView money;
    @Bind(R.id.lianjie)
    TextView lianjie;
    @Bind(R.id.ptitle)
    TextView ptitle;
    @Bind(R.id.banner)
    Banner banner;
    @Bind(R.id.paste)
    TextView paste;
    @Bind(R.id.save)
    TextView save;
    @Bind(R.id.quan)
    TextView quan;
    @Bind(R.id.beforeprice)
    TextView yuanPrice;
    @Bind(R.id.nowprice)
    TextView nowprice;
    @Bind(R.id.pic_view)
    LinearLayout pic_view;
    @Bind(R.id.shoucang)
    ImageView shoucang;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.zhuan)
    TextView tv_zhuan;
    @Bind(R.id.source)
    ImageView source;
    @Bind(R.id.collection_view)
    LinearLayout collection;
    @Bind(R.id.share_view)
    LinearLayout shareView;
    @Bind(R.id.shopname)
    TextView shopname;
    @Bind(R.id.textView3)
    TextView textView3;
    @Bind(R.id.shop)
    ImageView shop;
    @Bind(R.id.quanhou_back)
    TextView quanhouBack;
    @Bind(R.id.score1)
    TextView score1;
    @Bind(R.id.score2)
    TextView score2;
    @Bind(R.id.score3)
    TextView score3;
    @Bind(R.id.score_view)
    LinearLayout scoreView;
    @Bind(R.id.dianpu)
    LinearLayout dianpu;
    @Bind(R.id.tgwa)
    TextView tgwa;
    @Bind(R.id.oldwenan_view)
    LinearLayout oldwenanView;
    @Bind(R.id.coupon_time)
    TextView couponTime;
    @Bind(R.id.name2)
    TextView name2;
    @Bind(R.id.wenan)
    LinearLayout wenan;
    @Bind(R.id.coupnView)
    LinearLayout coupnView;
    @Bind(R.id.tv_quan)
    TextView tvQuan;
    @Bind(R.id.quan_view)
    LinearLayout quanView;
    @Bind(R.id.coupn)
    TextView coupn;
    @Bind(R.id.couponremain)
    TextView couponremain;
    @Bind(R.id.coupontotal)
    TextView coupontotal;
    private String collectionState;
    private String Tkl;
    private SharedPreferences sp;
    private String shareUrl;
    private SharedPreferences.Editor editor;
    private String itemid;
    private String youhuiquan;
    private String eventRate;
    private List<String> list = new ArrayList<>();
    private String maType;
    private TbDetailBean tbbena;
    private String h5, sourceType, salePrice, activityId;
    private int type = 0;
    private List<String> scoreList = new ArrayList<>();
    private List<String> picList = new ArrayList<>();


    @Override
    public int bindLayout() {
        return R.layout.activity_tb_detail;
    }

    @Override
    public void initView(View view) {
        sp = getSharedPreferences("user", MODE_PRIVATE);
        editor = sp.edit();
        maType = sp.getString("SpareTwo", "");
        yuanPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        title.setText("商品详情");
        CleanCacheUtil.clearAllCache(this);
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(5000);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        if (maType.equals("") || maType.equals("1")) {
            shareView.setVisibility(View.GONE);
        } else {
            shareView.setVisibility(View.VISIBLE);
        }
        back.setVisibility(View.VISIBLE);
        itemid = getIntent().getStringExtra("itemId");
        GetProductDetail();
        getState();
        back.setOnClickListener(this);
        lianjie.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        lianjie.getPaint().setAntiAlias(true);//抗锯齿
        share.setOnClickListener(this);
        copy.setOnClickListener(this);
        paste.setOnClickListener(this);
        coupn.setOnClickListener(this);
        collection.setOnClickListener(this);
        coupnView.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back: {
                finish();
            }
            break;
            case R.id.share: {
                if (null != tbbena && null != tbbena.getData()) {
                    Intent in = new Intent(TbProductDetailActivity.this, SharePictureActivity.class);
                    in.putExtra("quan", youhuiquan);
                    in.putExtra("price", salePrice);
                    in.putExtra("tkl", Tkl);
                    in.putExtra("h5", h5);
                    in.putExtra("sourceType", sourceType);
                    in.putExtra("salume", salenum.getText().toString());
                    in.putExtra("title", ptitle.getText().toString());
                    in.putExtra("type", ptitle.getText().toString());
                    in.putExtra("shop", shopname.getText().toString());
                    in.putStringArrayListExtra("imageList", (ArrayList<String>) list);
                    startActivity(in);
                }
            }
            break;
            case R.id.copy: {
                if (maType.equals("") || maType.equals("1")) {
                    dosure();
                } else {
                    if (RegexValidateUtils.isAppInstalled(this, "com.taobao.taobao")) {
                        openTaoBao();
                    } else {
                        ToastUtils.getInstance(TbProductDetailActivity.this).showMessage("请先安装淘宝");
                    }
                }
            }
            break;
            case R.id.quan_view: {
                if (maType.equals("") || maType.equals("1")) {
                    dosure();
                } else {
                    if (RegexValidateUtils.isAppInstalled(this, "com.taobao.taobao")) {
                        openTaoBao();
                    } else {
                        ToastUtils.getInstance(TbProductDetailActivity.this).showMessage("请先安装淘宝");
                    }
                }
            }
            break;
            case R.id.coupn: {
                if (maType.equals("") || maType.equals("1")) {
                    dosure();
                } else {
                    if (RegexValidateUtils.isAppInstalled(this, "com.taobao.taobao")) {
                        openTaoBao();
                    } else {
                        ToastUtils.getInstance(TbProductDetailActivity.this).showMessage("请先安装淘宝");
                    }
                }
            }
            break;
            case R.id.coupnView: {
                if (maType.equals("") || maType.equals("1")) {
                    dosure();
                } else {
                    if (RegexValidateUtils.isAppInstalled(this, "com.taobao.taobao")) {
                        openTaoBao();
                    } else {
                        ToastUtils.getInstance(TbProductDetailActivity.this).showMessage("请先安装淘宝");
                    }
                }
            }
            break;
            case R.id.couple: {
                if (maType.equals("") || maType.equals("1")) {
                    dosure();
                } else {
                    if (RegexValidateUtils.isAppInstalled(this, "com.taobao.taobao")) {
                        openTaoBao();
                    } else {
                        ToastUtils.getInstance(TbProductDetailActivity.this).showMessage("请先安装淘宝");
                    }
                }
            }
            break;
            case R.id.paste: {
                if (!TextUtils.isEmpty(tgwa.getText())) {
                    RegexValidateUtils.copyText(this, tgwa.getText().toString() + "\n" + "复制这条信息" + Tkl + "后打开手机淘宝即可查看");
                } else {
                    RegexValidateUtils.copyText(this, ptitle.getText().toString().replace("【", "").replace("】", "") + "\n" + money.getText().toString() + "\n" + nowprice.getText().toString() + "\n" + save.getText().toString() + "\n" + "复制这条信息" + Tkl + "后打开手机淘宝即可查看");
                }
                ToastUtils.getInstance(TbProductDetailActivity.this).showMessage("复制成功");
            }
            break;
            case R.id.collection_view: {
                if (null != collectionState && collectionState.equals("1")) {
                    CanceltheCollection();
                } else {
                    Collection();
                }
            }
            break;
            default:
                break;
        }
    }

    public void GetProductDetail() {
        mWeiboDialog = WeiboDialogUtils.createLoadingDialog(this);
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        HashMap<String, Object> map = new HashMap();
        map.put("Item_Id", itemid);
        map.put("UserPhone", sp.getString("userPhone", ""));
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).GetTBItemConvert(map, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "Item_Id" + itemid + "UserPhone" + sp.getString("userPhone", ""))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<TbDetailBean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onNext(TbDetailBean bean) {
                if (bean.getCode().equals("0")) {
                    DecimalFormat df = new DecimalFormat("0.00");
                    tbbena = bean;
                    if (null == bean.getData().getCoupon_start_time() || null == bean.getData().getCoupon_end_time() || bean.getData().getCoupon_start_time().equals("") || bean.getData().getCoupon_end_time().equals("")) {
                        coupn.setVisibility(View.VISIBLE);
                        coupnView.setVisibility(View.GONE);
                    } else {
                        coupn.setVisibility(View.GONE);
                        coupnView.setVisibility(View.VISIBLE);
                        couponTime.setText("有效期:" + bean.getData().getCoupon_start_time() + "—" + bean.getData().getCoupon_end_time());
                    }
                    if (null == bean.getData().getCoupon_remain_count() || null == bean.getData().getCoupon_total_count() || bean.getData().getCoupon_remain_count().equals("") || bean.getData().getCoupon_total_count().equals("")) {
                        coupnView.setVisibility(View.GONE);
                        coupn.setVisibility(View.VISIBLE);
                    } else {
                        coupnView.setVisibility(View.VISIBLE);
                        couponremain.setText(bean.getData().getCoupon_remain_count());
                        coupontotal.setText("/" + bean.getData().getCoupon_total_count() + "张");
                    }
                    activityId = bean.getData().getActivityId() == null ? "" : bean.getData().getActivityId();
                    shareUrl = bean.getData().getCoupon_click_url();
                    youhuiquan = bean.getData().getCoupon_info().replace(".00", "");
                    money.setText("◆原价:" + df.format(bean.getData().getZk_final_price()) + "元");
                    yuanPrice.setText("原价:" + df.format(bean.getData().getZk_final_price()));
                    salenum.setText("已售 " + bean.getData().getVolume());
                    shopname.setText(bean.getData().getNick());
                    sourceType = bean.getData().getUser_type();
                    salePrice = df.format(bean.getData().getZk_final_price());
                    h5 = bean.getData().getWxUrl();
                    Tkl = bean.getData().getTkl();
                    lianjie.setText(Tkl);
                    list = bean.getData().getImageUrl();
                    banner.setImages(list);
                    banner.start();
                    //banner设置方法全部调用完毕时最后调用
                    eventRate = bean.getData().getMax_commission_rate();
                    quanhou.setText("¥" + df.format(bean.getData().getPrice()));
                    SpannableString spannableString = new SpannableString(quanhou.getText().toString());
                    RelativeSizeSpan sizeSpan = new RelativeSizeSpan(1.2f);
                    spannableString.setSpan(sizeSpan, 0, quanhou.getText().toString().indexOf("."), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                    quanhou.setText(spannableString);
                    nowprice.setText("◆券后:" + df.format(bean.getData().getPrice()) + "元");
                    save.setText("◆节省:" + df.format(Double.parseDouble(bean.getData().getCoupon_info())) + "元");
                    ptitle.setText(bean.getData().getTitle());
                    name.setText(bean.getData().getTitle());
                    if (maType.equals("") || maType.equals("1")) {
                        ymoney.setVisibility(View.GONE);
                        paste.setVisibility(View.GONE);
                        tv_zhuan.setVisibility(View.GONE);
                        wenan.setVisibility(View.GONE);
                        upgrade.setText("升级超级教练可享佣金￥" + df.format(bean.getData().getCommission()));
                        if (Integer.parseInt(youhuiquan) > 0) {
                            copy.setText("自买省\n￥" + youhuiquan);
                        } else {
                            copy.setText("领券");
                        }
                    } else {
                        tv_zhuan.setVisibility(View.VISIBLE);
                        paste.setVisibility(View.VISIBLE);
                        if (maType.equals("2")) {
                            upgrade.setText("升级超级教练可享佣金￥" + df.format(bean.getData().getCommission()));
                            share.setText("分享赚\n￥" + df.format(bean.getData().getCommission() / 2));
                            tv_zhuan.setText("赚 ￥" + df.format(bean.getData().getCommission() / 2));
                            ymoney.setText("佣金:" + df.format(Double.parseDouble(eventRate) / 2) + "%");
                            if (Integer.parseInt(youhuiquan) > 0) {
                                copy.setText("自买省\n" + "￥" + youhuiquan + "+￥" + df.format(bean.getData().getCommission() / 2));
                            } else {
                                copy.setText("自买省\n" + "￥" + df.format(bean.getData().getCommission() / 2));
                            }
                        } else {
                            share.setText("分享赚\n￥" + df.format(bean.getData().getCommission()));
                            tv_zhuan.setText("赚 ￥" + df.format(bean.getData().getCommission()));
                            ymoney.setText("佣金:" + eventRate + "%");
                            upgrade.setVisibility(View.GONE);
                            if (Integer.parseInt(youhuiquan) > 0) {
                                copy.setText("自买省\n" + "￥" + youhuiquan + "+￥" + df.format(bean.getData().getCommission()));
                            } else {
                                copy.setText("自买省\n" + "￥" + df.format(bean.getData().getCommission()));
                            }
                        }
                    }
                    if (Integer.parseInt(youhuiquan) > 0) {
                        quan.setText(youhuiquan);
                        coupn.setText(youhuiquan + "元优惠券");
                    } else {
                        quan.setText("0");
                        coupn.setText("0元优惠券");
                    }
                    if (bean.getData().getUser_type().equals("0")) {
                        source.setImageResource(R.mipmap.tb);
                        shop.setImageResource(R.mipmap.tb);
                    } else {
                        source.setImageResource(R.mipmap.tm);
                        shop.setImageResource(R.mipmap.tm_shop);
                    }
                    GetTBDetailsNew();
                } else if (bean.getCode().equals("-1")) {
                    WeiboDialogUtils.closeDialog(mWeiboDialog);
                    commomDialog(bean.getMessage());
                } else if (bean.getCode().equals("-7")) {
                    WeiboDialogUtils.closeDialog(mWeiboDialog);
                    tokenDialog();
                }
            }
        });
    }

    public void GetCouponsNew() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).GetCouponsNew(itemid, activityId, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "itemid" + itemid + "couponid" + activityId)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<CouponBean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onNext(CouponBean bean) {
                if (bean.getCode().equals("0")) {
                    couponTime.setText("有效期:" + bean.getData().getCoupon_start_time() + "—" + bean.getData().getCoupon_end_time());
                }
            }
        });
    }

    public void getState() {
        String userName = sp.getString("userPhone", "");
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).GetState(userName, itemid, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "UserName" + userName + "ItemId" + itemid)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.getString("code").equals("1")) {
                    shoucang.setImageResource(R.mipmap.sc);
                    collectionState = "1";
                } else {
                    collectionState = "-1";
                    shoucang.setImageResource(R.mipmap.sc_);
                }
            }
        });
    }

    public void CanceltheCollection() {
        String userName = sp.getString("userPhone", "");
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).CanceltheCollection(userName, itemid, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "UserName" + userName + "ItemId" + itemid)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.getString("code").equals("1")) {
                    collectionState = "-1";
                    shoucang.setImageResource(R.mipmap.sc_);
                    ToastUtils.getInstance(TbProductDetailActivity.this).showMessage("取消收藏成功");
                } else {
                    collectionState = "1";
                    shoucang.setImageResource(R.mipmap.sc);
                    ToastUtils.getInstance(TbProductDetailActivity.this).showMessage("取消收藏失败");
                }
            }
        });
    }

    public void Collection() {
        String userName = sp.getString("userPhone", "");
        if (null != userName && null != tbbena && null != tbbena.getData().getUser_type() && null != tbbena.getData().getTitle() && null != tbbena.getData().getVolume() && null != tbbena.getData().getPict_url() && null != tbbena.getData().getCoupon_info() && null != tbbena.getData().getWxUrl()) {
            String price = tbbena.getData().getZk_final_price() + "";
            getCollection(userName, tbbena.getData().getPict_url(), tbbena.getData().getUser_type(), tbbena.getData().getTitle(), tbbena.getData().getVolume(), price);
        }
    }

    public void getCollection(String userName, String url, String type, String title, String volume, String price) {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        HashMap<String, Object> map = new HashMap();
        map.put("UserName", userName);
        map.put("ItemId", itemid);
        map.put("Url", url);
        map.put("Title", title);
        map.put("Price", price);
        map.put("Coupon", youhuiquan);
        map.put("Identification", type);
        map.put("volume", volume);
        map.put("ClickUrl", shareUrl);
        map.put("Commission", tv_zhuan.getText().toString());
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).YJCollection(map, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "ItemId" + itemid + "UserName" + userName + "Url" + url + "Title" + title + "Price" + price + "Coupon" + youhuiquan + "Identification" + type + "volume" + volume + "ClickUrl" + shareUrl + "Commission" + tv_zhuan.getText().toString())).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.get("code").equals("1")) {
                    collectionState = "1";
                    ToastUtils.getInstance(TbProductDetailActivity.this).showMessage("收藏成功");
                    shoucang.setImageResource(R.mipmap.sc);
                } else {
                    collectionState = "-1";
                    ToastUtils.getInstance(TbProductDetailActivity.this).showMessage("收藏失败");
                    shoucang.setImageResource(R.mipmap.sc_);
                }
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
    }


    public void RequestData() {
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).SetTkl(shareUrl).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<TklBean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                Log.d(TAG, "onError: --------------" + "onError" + e.toString());
            }

            @Override
            public void onNext(TklBean bean) {
                if (bean.getCode().equals("0")) {
                    Tkl = bean.getData().getTbk_tpwd_create_response().getData().getModel();
                    lianjie.setText(Tkl);
                }
            }
        });
    }

    public void dosure() {
        new CommonDialog.Builder(this)
                .setTitle("提示")
                .setMessage("此操作不可撤销，请确认余额" + youhuiquan + "元兑换此产品")
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Duihuan();
                    }
                })
                .setNegativeButton("取消", null).show();
    }

    public void openTaoBao() {                      //唤醒淘宝
        //提供给三方传递配置参数
        ToastUtils.getInstance(TbProductDetailActivity.this).showMessage("正在打开淘宝....");
        Map<String, String> exParams = new HashMap<>();
        exParams.put(AlibcConstants.ISV_CODE, "appisvcode");
        AlibcShowParams showParams = new AlibcShowParams(OpenType.Native, false);
        AlibcBasePage page = new AlibcPage(shareUrl);
        AlibcTrade.show(TbProductDetailActivity.this, page, showParams, null, exParams,
                new AlibcTradeCallback() {

                    @Override
                    public void onFailure(int i, String s) {

                    }

                    @Override
                    public void onTradeSuccess(TradeResult tradeResult) {

                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mWeiboDialog) {
            mWeiboDialog.cancel();
        }
    }

    public void Duihuan() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).SetBuy(sp.getString("userPhone", ""), youhuiquan, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "UserPhone" + sp.getString("userPhone", "") + "Money" + youhuiquan)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject obj) {
                if (obj.getString("code").equals("0")) {
                    if (RegexValidateUtils.isAppInstalled(TbProductDetailActivity.this, "com.taobao.taobao")) {
                        ToastUtils.getInstance(TbProductDetailActivity.this).showMessage("兑换成功");
                        openTaoBao();
                    } else {
                        ToastUtils.getInstance(TbProductDetailActivity.this).showMessage("请先安装淘宝");
                    }
                } else if (obj.getString("code").equals("-1")) {
                    ToastUtils.getInstance(TbProductDetailActivity.this).showMessage("兑换失败");

                } else if (obj.getString("code").equals("-2")) {
                    ToastUtils.getInstance(TbProductDetailActivity.this).showMessage("余额不足，请充值");
                }
            }
        });
    }

    public void addView() {
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        lp.setLayoutDirection(LinearLayout.VERTICAL);
        pic_view.setLayoutParams(lp);
        for (int i = 0; i < picList.size(); i++) {
            ImageView imageView = new ImageView(this);
            Glide.with(this).load(picList.get(i)).into(imageView);
            pic_view.addView(imageView);
        }
    }

    public void GetTBDetailsNew() {
        final String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).GetTBDetailsNew(itemid, sourceType, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "ItemId" + itemid + "category" + sourceType)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<TbImageDetailBean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onNext(TbImageDetailBean bean) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
                if (bean.getCode().equals("0")) {
                    if (null != bean.getData() && null != bean.getData().get(0)) {
                        scoreList = bean.getData().get(0).getScore();
                        picList = bean.getData().get(0).getImg();
                        scoreView.setVisibility(View.VISIBLE);
                        if (scoreList.size() > 0) {
                            score1.setText(scoreList.get(0));
                            score2.setText(scoreList.get(1));
                            score3.setText(scoreList.get(2));
                        } else {
                            score1.setText("4.8");
                            score2.setText("4.8");
                            score3.setText("4.8");
                        }
                        if (picList.size() > 0) {
                            addView();
                        }
                        if (bean.getData().get(0).getCopywriting().trim().equals("")) {
                            oldwenanView.setVisibility(View.VISIBLE);
                            tgwa.setVisibility(View.GONE);
                        } else {
                            oldwenanView.setVisibility(View.GONE);
                            tgwa.setVisibility(View.VISIBLE);
                            tgwa.setText(bean.getData().get(0).getCopywriting());
                        }
                    }
                } else {
                    oldwenanView.setVisibility(View.VISIBLE);
                    tgwa.setVisibility(View.GONE);
                    score1.setText("4.8");
                    score2.setText("4.8");
                    score3.setText("4.8");
                }
            }
        });
    }

    public void commomDialog(String Message) {
        new CommonDialog.Builder(this)
                .setTitle("提示")
                .setMessage(Message)
                .setMessageGravity()
                .setCanceledOnTouchOutside(false)
                .setPositiveButton("我知道了", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        finish();
                    }
                }).show();
    }

    private void tokenDialog() {
        //这里不发送检测新版本网络请求，直接进入下载新版本安装
        final CommonDialog.Builder builder = new CommonDialog.Builder(this, 1, 1);
        builder.setMessage("应淘宝优化需求，为使您的数据更精准，账号更安全，需授权后使用！");
        builder.setCancelable(false);
        builder.setPositiveButton("前往淘宝授权", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login();
                builder.dismiss();

            }
        });
        builder.setNegativeButton(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
        builder.create().show();
    }

    @Override
    public void onPause() {
        super.onPause();
        banner.stopAutoPlay();
    }

    @Override
    public void onStart() {
        super.onStart();
        banner.startAutoPlay();
    }

    public void login() {
        LoginService loginService = MemberSDK.getService(LoginService.class);
        if (loginService != null) {
            loginService.auth(this, new LoginCallback() {
                @Override
                public void onSuccess(Session session) {
                    Intent in = new Intent(TbProductDetailActivity.this, WebViewActivity.class);
                    in.putExtra("url", "https://oauth.taobao.com/authorize?response_type=code&client_id=24895091&redirect_uri=http://www.taohuikeji.com&view=wap");
                    in.putExtra("title", "淘宝授权");
                    startActivity(in);
                }

                @Override
                public void onFailure(int code, String msg) {

                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        CallbackContext.onActivityResult(this, requestCode, resultCode, data);
    }
}
